<html>
<head>
    <link rel="stylesheet" href="/assets/style.css" type="text/css" />
    <script src='/_ah/channel/jsapi'></script>
    <script type="text/javascript">
      // vars
      var host = "{{ host }}";
      var hostname = window.location.hostname;
      var port = window.location.port;
      var url2 = "https://" + hostname + ":" + port + "/dispatch/";
      var url = "http://" + hostname + ":" + port + "/dispatch/";
      var got = hostname.indexOf("localhost");
      var starttime = new Date();
      var interval_id;
      var lastpolled = new Date();
      var lpdate = lastpolled.getTime();
      var sleeptime = 180000;
      var host = "";
      var viewer = "";
      var hostid = "";
      var viewerid = "";
      var parameters = "";
      var identtime = new Date();
      var diskname = host + identtime.toString();
      var consoletxt = '<div style="font-size: 25px;"><br><form><b>&lt;-</b><input style="font-size: 80%;" size="33" type="text" name="cmnd" onKeyDown="return doexec(this.form, event);" /><b>-&gt;</b></form></div><div class="related"><div align="center" id="status_div" style="background-color: #803E3E;"><b>JSONBOT PRESENT!<b></div></div>';
      var feedstxt = '<br><form name="feeddata" action="javascript:submitfeed(this.form);" method="GET"><b>feed name - </b> <input type="text" name="name" /><br></b><b>feed url - </b> <input type="text" name="url" onKeyPress="return doenter(this.form, event);" /><br><br><input type="submit" name="Enter" onClick="return submitfeed(this.form);"/><input type="reset" name="reset" /></form><div class="body" align="left" id="content_div"><i>no feeds entered yet.</i></div>';
      var log = new Array();
      var cmndlog = new Array();
      var disk = {};
      var topperlist = new Array();

      function scrollToBottom(elm_id) {
	var elm = document.getElementById(elm_id);
        var f = document.createElement("input");
        if (f.setAttribute) f.setAttribute("type","text")
        if (elm.appendChild) elm.appendChild(f);
        f.style.width = "0px";
        f.style.height = "0px";
        if (f.focus) f.focus();
        if (elm.removeChild) elm.removeChild(f);
      }


      // clear div

      function clear(divname) {
        var element = document.getElementById(divname);  
        element.innerHTML = "<b>[!]</b>";
      }

      // channel stuff

      function renewtoken(obj) {
           if (obj.readyState==4) {
               if (obj.status==200) {
                   var token = obj.responseText;
                   //status2("token is " + token);
                   openChannel(token);
                   info("token renewed on " + contime.toTimeString() + "<br>");
                   output("token renewed on " + contime.toTimeString() + "<br>");
              }
          }
      }

      onOpened = function() {
        contime = new Date();
        topperpush("channel opened on " + contime.toTimeString());
        info("channel opened on " + contime.toTimeString() + "<br>");
        //output("channel opened on " + contime.toTimeString() + "<br>");
      }

      onClose = function() {
        topperpush("channel closed on " + contime.toTimeString());
        info("channel closed on " + contime.toTimeString() + "<br>");
        //output("channel closed on " + contime.toTimeString() + "<br>");
        doCmnd('!chan-token', renewtoken, 'background'); 
      }

      onMessage = function(m) {
        output(m.data);
        var index1 = m.data.indexOf("http://");
        var index2 = m.data.indexOf("https://");
        if (index1 > -1) {
            topperpush(m.data);
        }
        else if (index2 > -1) {
            topperpush(m.data);
        }
      }

      onError = function(m) {
        // newState = JSON.parse(m.data);
        status(m.data);
        info(m.data);
      }

      openChannel = function(token) {
        info("opening channel on " + "{{ host }}");
        statusadd("- iframe");
        thediv = document.getElementById("wcs_iframe");
        if (thediv) {
            document.removeChild(thediv);
        }
        statusadd(" - channel");
        var channel = new goog.appengine.Channel(token);
        statusadd(" - socket - ");
        var socket = channel.open();
        socket.onopen = onOpened;
        socket.onmessage = onMessage;
        socket.onerror = onError;
        socket.onclose = onClose;
        statusadd(elapsed() + " msec - ");
        statusadd("OK");
      }

      // utils functions

      function elapsed() {
        last = new Date();
        diff = last.getTime() - starttime.getTime();
        starttime = last;
        return diff;
      }

      // mainloop

      function updateloop() {
        update();
      }

      function outputloop() {
        var show = topperlist.pop();
        if (show) {
          topper(show);
        }
      }        

      // time loop

      function timeloop() {
        var now = new Date();
        uber("<b>" + now.toTimeString() + "</b>");
      }


      // INIT

      function start() {
          loaddisk();
          doCmnd('!chan-token', renewtoken, 'background'); 
          update();
          setTimeout("doCmnd('!welcome', dotop, 'background');", 300);
          setTimeout("doCmnd('!topper', doinfo, 'background');", 10000);
          setTimeout("doCmnd('!statusline', doinfo, 'background');", 20000);
          setInterval("updateloop();", 30000);
          setInterval("timeloop();", 1000);
          setInterval("outputloop();", 30000);
          setTimeout("outputloop();", 1000);
      }


      function init() {
        setTimeout("consolestart();", 100)
      }

      function consolestart() {
          doconsole();
          status("<b>BOOTING</b>");
          setTimeout("start();", 100);
          //statusadd(elapsed() + " msec ");
      }

      function update(what) {
        savedisk();
        updatetime = new Date();
      }

      function doconsole() {
        doscreen(consoletxt);
        document.forms[0].cmnd.focus();
      }

      function dofeeds() {
        doscreen(feedstxt);
        document.forms[0].name.focus();
      }

      function loaddisk() {
        if (!localStorage) { 
          output("no local storage available");
        }
        else {
          statusadd(" - disk ");
          data = localStorage.getItem(host +"-disk");
          if (!data) {
            disk["cmndindex"] = 0;
          }
          else {
            disk = JSON.parse(data)
          }
        }
      } 

      function savedisk() {
        if (!localStorage) {
          status("no local storage available");
        }
        else {
          var data = JSON.stringify(disk);
          if (!data) {
            output("can't dump disk data");
          }
          else {
            localStorage.setItem(host + "-disk", data);
          }
        }
      } 

      // submit feed url to the server

      function submitfeed(form) {
           cmnd = "!rss-register " + form.name.value + " " + form.url.value;           
           doCmnd(cmnd, response);
           return false;
      } 

      // function to launch on enter in the command box

      function doenter(form, e) {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
           else if (e) keycode = e.which;
        else return true;
        if (keycode == 13)
        {
           cmnd = "!rss-register " + form.name.value + " " + form.url.value;           
           doCmnd(cmnd, response, "background");
           return false;
        }
        else
          return true;
      }

      function doexec(form, e) {
        var keycode;
        var othercmnd;
        if (window.event) keycode = window.event.keyCode;
           else if (e) keycode = e.which;
        else return true;
        if (keycode == 13) {
           cmnd = form.cmnd.value; 
           doCmnd(cmnd, response);
           cmndlog.push(cmnd);
           disk["cmndindex"] += 1;
           form.cmnd.value = "";
           form.focus();
           return false;
        }
        else if (keycode == 38) {
           if (disk["cmndindex"] > 1) {
               disk["cmndindex"] -= 1;
           }
           othercmnd = cmndlog[disk["cmndindex"]];
           form.cmnd.value = othercmnd;
           form.focus();
           status(othercmnd);
           return false;
        }
        else if (keycode == 40) {
           if (disk["cmndindex"] < cmndlog.length) {
               disk["cmndindex"] += 1;
           }
           othercmnd = cmndlog[disk["cmndindex"]];
           form.cmnd.value = othercmnd;
           form.focus();
           status(othercmnd);
           return false;
        }
        else
          return true;
      }

      // output functions

      function output(text) {
        log.push(text);
        var element = document.getElementById("content_div");  
        element.innerHTML += text;
        scrollToBottom("content_div");
        document.forms[0].cmnd.focus();
      }

      function uber(text) {
        var html = text;
        var element = document.getElementById("uber_div");  
        element.innerHTML = html;
      }

      function down(text) {
        var html = text;
        var element = document.getElementById("down_div");  
        element.innerHTML = html;
      }

      function info(text) {
        var html = "<i>";
        html += text;
        html += "</i>";

        var element = document.getElementById("info_div");  
        element.innerHTML = html;
        //setTimeout("clear('info_div');", 10000);
      }

      function footer(text) {
        var html = "<i>";
        html += text;
        html += "</i>";

        var element = document.getElementById("footer_div");  
        element.innerHTML = html;
      }

      function topper(text) {
        var html = '<marquee align="center" behavior="slide" scroll-delay="20" direction="left">';
        html += text;
        html += "</marquee>";
        var element = document.getElementById("topper_div");  
        element.innerHTML = html;
      }

      function topperpush(text) {
        topperlist.unshift(text);
      }

      function statusadd(text) {
        var html = '';
        html += text;
        html += "";
        var element = document.getElementById("status_div");  
        element.innerHTML += html;
      }

      function status(text) {
        var html = '';
        html += text;
        html += "";

        var element = document.getElementById("status_div");  
        element.innerHTML = html;
      }

      function status2add(text) {
        var html = "<b>";
        html += text;
        html += "</b>";

        var element = document.getElementById("status2_div");  
        element.innerHTML += html;
      }

      function status2(text) {
        var html = "<b>";
        html += text;
        html += "</b>";

        var element = document.getElementById("status2_div");  
        element.innerHTML = html;
      }

      function doscreen(screentxt) {
        var element = document.getElementById("screen_div");  
        element.innerHTML = screentxt;
      }

      // response functions

      function response(obj) {
          if (obj.readyState==4){
              if (obj.status==200) {
                   output(obj.responseText);
                   statusadd(" " + elapsed() + " msec - OK");
              }
              else {
                   statusadd(" " + elapsed() + " msec - NOT OK");
                   topper("status is " + obj.status);
                   output(obj.responseText);
              }
              update();
          }
      }

      function dodown(obj) {
          if (obj.readyState==4) {
              if (obj.status==200) {
                  down(obj.responseText);
              }
          }
      }

      function dotop(obj) {
          if (obj.readyState==4) {
              if (obj.status==200) {
                  topperpush(obj.responseText);
              }
          }
      }

      function dostatus(obj) {
           if (obj.readyState==4) {
               if (obj.status==200) {
                   status(obj.responseText);
              }
          }
      }

      function doinfo(obj) {
           if (obj.readyState==4) {
               if (obj.status==200) {
                   info(obj.responseText);
              }
          }
      }

      function doCmnd(cmnd, resp, how) {
          var request = false;
          if (window.XMLHttpRequest) {
              request = new XMLHttpRequest();
          }
          else if (window.ActiveXObject) { 
              try {
                  request = new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
                  try {
                      request = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (e) {}
              }
          }

          if (!request) {
              topper("can't make connection to server");
              return false;
          }

          request.cmnd = cmnd;
          request.how = how;
          request.onreadystatechange = function () {
              resp(request);
          }
          var u = "";
          if (got == -1) {
              request.open("POST", url2, true);
              u = url2;
          }
          else {
              request.open("POST", url, true);
              u = url;
          }
          if (how != "background") {
              status("sending command - ");
          }
          request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          request.setRequestHeader("Content-Length", parameters.length);
          request.setRequestHeader("Cache-Control", "no-cache");
          parameters="content="+encodeURIComponent(cmnd) + "&how=" + encodeURIComponent(how);
          starttime = new Date();
          request.send(parameters);
          return true;
      }
   </script>
</head>
<body>
  <title>{{ host }}</title>
  <div align="center" class="document">
    <div class="related" style="font-size: 100%">
      <ul>
        <li class="right" style="margin-right: 10px;">
          <a href="{{ logouturl }}" title="logout">logout</i></a></li>
        <li class="right" style="margin-right: 10px;">{{ who }}<b> - </b></li>
        <li><a href="http://jsonbot.appspot.com/docs/html/index.html" onclick='window.open("http://jsonbot.appspot.com/docs/html/index.html"); return false'><b>DOCS</b></a></li>
        <li>-</li>
        <li><a href="" title="console" onclick='doconsole(); return false;'><b>console</b></a></li>
        <li>-</li>
        <li><a href="" title="feeds" onclick='dofeeds(); return false;'><i>feeds</i></a></li>
      </ul>
    </div>
    <div align="center" id="uber_div" style="font-size: 100%; background-color: white; color: black;">Morning !!</div>
    <div class="body" align="center"><h1 style="background-color: {{ color }}; color: white;"><b>{{ appname }}</b></h1>
      <div style="width: 100%; font-size: 100%; font-weight: bold; color: white;" align="center" id="topper_div">[] [] []</div>
    </div>
        <div class="output" align="center" style="position: float;">
          <div style="width: 90%; font-size: 100%" scroll="auto" align="center" id="content_div"></div>
        </div>
      </div>
      </div>
      <div class="bottom" style="width: 100%; font-size: 100%; font-weight: bold;" align="center">
        <div class="footer" style="font-size: 100%; font-height: 80%; color: white;" align="center" id="info_div">[] [] []</div><br>
        <div style="font-size: 100%; width: 100%; background-color: {{ color }}; color: white;" position="fixed" bottom="0""  id="screen_div"></div>
      </div>
    </div>
  </div>
</body>
<body onLoad="init();" />
</html>
